﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

using G28BS.Models;
using G28BS.GameModels;

namespace G28BS.Hubs
{
    public class FimbulfambHub : MasterHub
    {
        private FimbulfambQueries _ffQueries = new FimbulfambQueries();
        private JavaScriptSerializer _serializer = new JavaScriptSerializer();

        public void LogResults(string groupID, string playerScores)
        {
            // playerScores contains a 2D array of players userProfileID and ending score.
        }

        public void UpdateSettings(string groupID, string s)
        {
            // Call the UpdateModel method on fimbulFamb.
            Clients.Group(groupID).updateSettings(s);
        }

        public void UpdateRound(string groupID, string r)
        {
            // Call the UpdateRound method on fimbulFamb.
            Clients.Group(groupID).updateRound(r);
        }

        public void UpdateScores(string groupID, string ps)
        {
            // Call the UpdateScores method on fimbulFamb.
            Clients.Group(groupID).updateScores(ps);
        }

        public void StartRound(string groupID, int wordID)
        {
            var word = _ffQueries.GetWordByID(wordID);
            // Call the UpdateModel method on fimbulFamb.
            Clients.Caller.startRound(_serializer.Serialize(word));
        }

        // Overridden method of MasterHub.
        public override void StartGame(string groupID, int gameRoomID)
        {
            try
            {
                _UpdateGameRoomState(gameRoomID, GameRoomStates.Active);
            }
            catch (KeyNotFoundException e)
            {
                Clients.Group(groupID).error(e.Message);
            }
            // Notify gamerooms in group about state change.
            Clients.Group(groupID).updateState(GameRoomStates.Active.ToString());
            // And Fimbulfamb applications also.
            var wordIDs = _ffQueries.GetShuffledWordIDs();
            // Send wordIDs to all games as JSON.
            Clients.Group(groupID).startGame(_serializer.Serialize(wordIDs));
        }
    }
}